package org.javaboy.demo.config;

import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRegistration;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

/**
 * 这个类的作用就类似于 web.xml
 */
public class WebInit implements WebApplicationInitializer {
    /**
     * 当启动启动的时候，这个方法会被触发，我们就可以在这里初始化 Spring 容器
     *
     * @param servletContext
     * @throws ServletException
     */
    @Override
    public void onStartup(ServletContext servletContext) throws ServletException {
        AnnotationConfigWebApplicationContext ctx = new AnnotationConfigWebApplicationContext();
        //加载两个配置类
        ctx.register(SpringConfig.class, SpringMVCConfig.class);
        //将 Servlet 容器设置给 Spring
        ctx.setServletContext(servletContext);
        ServletRegistration.Dynamic springmvc = servletContext.addServlet("springmvc", new DispatcherServlet(ctx));
        springmvc.addMapping("/");
    }
}
